﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using System.Text;

namespace Thermerators
{
    public class Program
    {
        private static TMP36 tempSensor1;
        private static TMP36 tempSensor2;
        private static Servo servo;
        private static double curDesiredTemp;

        public static void Main()
        {
            tempSensor1 = new TMP36(new AnalogInput(Pins.GPIO_PIN_A0),100);
            tempSensor2 = new TMP36(new AnalogInput(Pins.GPIO_PIN_A1),100);
            //servo = new Servo(Pins.GPIO_PIN_D0);
            //closeValve();
            ServerSocket.listen(8877);
            curDesiredTemp = 80;
            (new Thread(new ThreadStart(updateTemperatureData))).Start();
            while(true)
            {
                //Debug.Print("T1:" + tempSensor1.convertToF(tempSensor1.read()));
                //Debug.Print("T2:" + tempSensor2.convertToF(tempSensor2.read()));
            }

        }

        public static void updateTemperatureData()
        {
            while (true)
            {
                Thread.Sleep(10000);
                double curTemperature = tempSensor1.convertToF(tempSensor1.read());
                sendToAll("cur~" + curTemperature);
            }
        }

        public static void sendToAll(String message)
        {
            ArrayList ids = ServerSocket.getConnectionIDs();
            double curTemperature = tempSensor1.convertToF(tempSensor1.read());
            for (int i = 0; i < ids.Count; i++)
            {
                ServerSocket.sendMessage((int)ids[i], message);
            }
        }

        public static void openValve()
        {
            if (servo != null)
                servo.Degree = 50;
        }

        public static void closeValve()
        {
            if(servo != null)
                servo.Degree = 0;
        }

        public static double getCurDesiredTemperature()
        {
            return curDesiredTemp;
        }

        public static void setCurDesiredTemp(double value)
        {
            curDesiredTemp = value;
            sendToAll("des~" + value);
        }
    }
}
